//
//  ICContactsSearchController.m
//  ICome
//
//  Created by zhangrongwu on 2017/12/1.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICContactsSearchController.h"
#import "ICTitleView.h"
#import "ICContactListCell.h"
#import "NSMutableAttributedString+Extension.h"
#import "ICHeaderFile.h"
#import "ICOrganizationViewController.h"
#import "iComeApiManager.h"

@interface ICContactsSearchController ()<UITableViewDelegate, UITableViewDataSource, ICTitleViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *dataList;
@property (nonatomic, strong)UILabel * emptyStyleLable;
@property (nonatomic, strong)NSString *searchText;
@property (nonatomic, strong)ICTitleView *titleView;
@end

@implementation ICContactsSearchController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupSubView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self.titleView.searchBar resignFirstResponder];
}

#pragma mark - UITableViewDataSource

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"ICContactListCell";
    ICContactListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICContactListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.leftFreeSpace = 0;
    
    ICEmpInfoModel *model = [self.dataList objectAtIndex:indexPath.row];
    if (model.isOrg) {
        NSString *searchTitle = [NSString stringWithFormat:@"%@   (%ld)", model.oName, (long)model.count];
        cell.titleLabel.attributedText = [NSMutableAttributedString searchTtitle:searchTitle key:self.searchText keyColor:SEARCH_HEIGHT_COLOR];
        NSString *URL = [ICTools getMinImageURL:(model.photoId)];
        [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:URL] placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_organization"]];
        cell.subTitleModel = model;
    } else {
        NSString *searchTitle = [NSString stringWithFormat:@"%@   (%@)", model.eName, model.jobTitle];
        cell.titleLabel.attributedText = [NSMutableAttributedString searchTtitle:searchTitle key:self.searchText keyColor:SEARCH_HEIGHT_COLOR];
        NSString *URL = [ICTools getMinImageURL:model.photoId];
        [UIImage addAvatariamgeView:cell.headImageView withUrlStr:URL witheId:model.eId withName:model.eName];
        cell.subTitleModel = model;
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 66.0f * Level;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICEmpInfoModel *model = [self.dataList objectAtIndex:indexPath.row];
    if (model.isOrg)
    {
        if ([ICTools stringEmpty:(model.oId)]) {
            [MBProgressHUD showError:@"该员工不存在~"];
            return;
        }
        ICOrganizationViewController *vc = [[ICOrganizationViewController alloc] init];
        vc.CtrStyle = CtrStyleOther_sdk;
        vc.oId = model.oId;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        NSDictionary *param = @{@"eId":model.eId};
        if ([model.eId rangeOfString:@"bot"].location == NSNotFound) {
            if ([[iComeApiManager instance].delegate respondsToSelector:@selector(openContactsDetailsFromViewC::)]) {
                [[iComeApiManager instance].delegate openContactsDetailsFromViewC:self:param];
            } else {
                UIViewController * vc = [[IComMediator sharedInstance] IComMediator_ContactsDetailViewController:param];
                [self.navigationController pushViewController:vc animated:YES];
            }
        }else
        {
            UIViewController *vc = [[IComMediator sharedInstance] IComMediator_RobotDetailViewController:param];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.titleView.searchBar resignFirstResponder];
}

#pragma mark - private

- (void)reloadTableViewWithData:(id)response {
    [self.dataList removeAllObjects];
    NSDictionary *dict = [response objectForKey:@"data"];
    NSArray *employeeList = [dict objectForKey:@"employeeList"];
    NSArray *orgList = [dict objectForKey:@"orgList"];
    if (employeeList.count > 0 || orgList.count > 0) {
        self.emptyStyleLable.hidden = YES;
    } else {
        self.emptyStyleLable.hidden = NO;
    }
    for (NSDictionary *empdict in employeeList) {
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] initWithDict:empdict];
        [self.dataList addObject:model];
    }
    
    for (NSDictionary *orgdict in orgList) {
        ICEmpInfoModel *model = [[ICEmpInfoModel alloc] initWithDict:orgdict];
        [self.dataList addObject:model];
    }
    [self.tableView reloadData];
}

#pragma mark - Private

- (void)setupSubView
{
    self.view.backgroundColor = BACKGROUNDCOLOR;
    self.navigationController.navigationBarHidden = YES;
    self.titleView = [[ICTitleView alloc] initWithFrame:CGRectMake(0, 0, App_Frame_Width, [ICTools getNavbarHeight]+[ICTools getStatusbarHeight])];
    self.titleView.delegate     = self;
    self.titleView.backgroundColor  = NE_BACKGROUND_COLOR;
    self.titleView.searchBar.backgroundColor = [ICTools getRgbColor:0x5CACFE];
    self.titleView.searchBar.tintColor = [UIColor whiteColor];
    self.titleView.searchBar.textColor = [UIColor whiteColor];
    [self.titleView.searchBar setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    UIImage *image = [UIImage  imageNamedFromiComeSDKBundle:@"icon_search"];
    self.titleView.searchBar.iconImage.image = [image imageWithColor:[UIColor whiteColor]];
    [self.view addSubview:self.titleView];
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame        = CGRectMake(0, self.titleView.bottom, self.view.width, self.view.height-self.titleView.height);
    tableView.delegate     = self;
    tableView.dataSource   = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView];
    self.tableView = tableView;
}

#pragma mark - titleViewDelegate

- (void)cancelBtnClicked
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchText:(NSString *)text
{
    self.dataList  = nil;
    self.searchText = text;
    self.emptyStyleLable.hidden = YES;
    if ([ICTools stringEmpty:(text)]) {
        [self.tableView reloadData];
        self.emptyStyleLable.hidden = NO;
        return;
    }
    NSDictionary *param = @{@"key":text};
    [[ICSocketRequestManager sharedInstance] contactSearchListWithObject:param Success:^(id object) {
        [self reloadTableViewWithData:object];
    } Failure:^(NSError *error, id other) {
        [MBProgressHUD showError:error.domain];
        [self.tableView reloadData];
    }];
}

#pragma mark - Getter

- (NSMutableArray *)dataList
{
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
    }
    return _dataList;
}

- (UILabel *)emptyStyleLable
{
    if (!_emptyStyleLable) {
        _emptyStyleLable       = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, App_Frame_Width, 30)];
        _emptyStyleLable.font  = [UIFont systemFontOfSize:17];
        _emptyStyleLable.backgroundColor = [UIColor clearColor];
        _emptyStyleLable.textAlignment = NSTextAlignmentCenter;
        _emptyStyleLable.textColor     = ICRGB(0x9a9a9a);
        _emptyStyleLable.text = @"暂无搜索结果";
        [self.tableView addSubview:_emptyStyleLable];
    }
    return _emptyStyleLable;
}

@end
